<?php
require_once(dirname(__FILE__) . '/../init.php');

$di = \PhalApi\DI();
$dbCfg = $di->config->get("dbs.servers.db_master");
if (empty($dbCfg)) {
	die('缺少数据库配置');
}

// Autoloading (composer is preferred, but for this example let's just do this)
require_once(API_ROOT . '/oauth2-server-php/src/OAuth2/Autoloader.php');
\OAuth2\Autoloader::register();

$dsn = sprintf('mysql:dbname=%s;host=%s;port=%d',
	$dbCfg['name'],
	isset($dbCfg['host']) ? $dbCfg['host'] : 'localhost',
	isset($dbCfg['port']) ? $dbCfg['port'] : 3306
);

$config = array(
	'client_table' => 'oauth_clients',
	'access_token_table' => 'oauth_access_tokens',
	'refresh_token_table' => 'oauth_refresh_tokens',
	'code_table' => 'oauth_authorization_codes',
	'user_table' => 'oauth_users',
	'jwt_table'  => 'oauth_jwt',
	'jti_table'  => 'oauth_jti',
	'scope_table'  => 'oauth_scopes',
	'public_key_table'  => 'oauth_public_keys',
);
        
//$dsn      = 'mysql:dbname=my_oauth2_db;host=localhost';
//$username = 'root';
//$password = '';

// error reporting (this is a demo, after all!)
//ini_set('display_errors',1);
//error_reporting(E_ALL);

// $dsn is the Data Source Name for your database, for exmaple "mysql:dbname=my_oauth2_db;host=localhost"
//$storage = new OAuth2\Storage\Pdo(array('dsn' => $dsn, 'username' => $username, 'password' => $password));
$storage = new \OAuth2\Storage\Pdo(array('dsn' => $dsn, 'username' => $dbCfg['user'], 'password' => $dbCfg['password']), $config);

// Pass a storage object or array of storage objects to the OAuth2 server class
$server = new OAuth2\Server($storage);

// Add the "Client Credentials" grant type (it is the simplest of the grant types)
//$server->addGrantType(new OAuth2\GrantType\ClientCredentials($storage));

// Add the "Authorization Code" grant type (this is where the oauth magic happens)
//$server->addGrantType(new OAuth2\GrantType\AuthorizationCode($storage));

// create the grant type
$grantType = new OAuth2\GrantType\UserCredentials($storage);
// add the grant type to your OAuth server
$server->addGrantType($grantType);

